package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
)
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
)

func HelloHandler(w http.ResponseWriter, r *http.Request) {
	//Header信息
	for key, value := range r.Header {
		w.Header().Set(key, strings.Join(value, ""))
	}
	//VERSION 配置
	envs := os.Environ()
	for _, e := range envs {
		parts := strings.SplitN(e, "=", 2)
		if len(parts) != 2 {
			continue
		}else{
			w.Header().Set(parts[0], parts[1])
		}
	}
	w.WriteHeader(http.StatusOK)
	log.Printf("客户端 IP:%d,HTTP 返回码:%d", RemoteIp(r),http.StatusOK)
}
func RemoteIp(req *http.Request) string {
	remoteAddr := req.RemoteAddr
	if ip := req.Header.Get(XRealIP); ip != "" {
		remoteAddr = ip
	} else if ip = req.Header.Get(XForwardedFor); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}

	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}

	return remoteAddr
}
func HelloHandlerthz(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w,strconv.Itoa(http.StatusOK))
	log.Printf("HTTP 返回码:%d", http.StatusOK)
}

func main () {
	http.HandleFunc("/", HelloHandler)
	http.HandleFunc("/healthz", HelloHandlerthz)
	http.ListenAndServe(":80", nil)
}
